<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <e-cellbox middle class="student-manage">
          <e-cell-item>
            <e-heading grade='1'>学员列表</e-heading>
          </e-cell-item>
          <e-cell-item class="tr weak">
            <el-button type="link"  @click="beforeDownloadExcel">下载模板</el-button>
            <e-file-upload
              style="position:relative"
              accept=".xlsx,.xls"
              class="upload-demo"
              :action="uploadUrl"
              :on-error="errorUpload"
              @success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :show-file-list="false"
              @exception="hanleException">
              <el-button size="small" title="点击上传文件“批量新增学员.xlsx”">导入学员</el-button>
            </e-file-upload>
            <el-button size="small" @click="handleExportStudent" :disabled="train_student_list.list && train_student_list.list.length === 0">导出学员</el-button>
            <el-button size="small" @click="handleAddStudent" type="primary">添加学员</el-button>
          </e-cell-item>
        </e-cellbox>
      <div class="search-mines">
        <el-form v-bind="getFormProps()" :inline="true">
          <el-form-item label="姓名：">
            <el-input v-model="query.name" size="small" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="校区：">
            <el-select v-model="schoolCampus" clearable placeholder="请选择校区" style="width: 88%;" @change="campusChange">
              <el-option v-for="item in campusData" :key="item.id" :label="item.schoolName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄范围：" class="age-box">
            <e-input-number-range v-model="numberRange" size="small"/>
          </el-form-item>
          <el-button size="small" type="primary-plain" class="search-btn search-student" native-type="submit">搜索</el-button>
        </el-form>
      </div>
      <e-cellbox middle class="selected_student_list">
        <e-cell-item>
          <el-checkbox v-model="query.showInClass">只看有课的学员</el-checkbox>
        </e-cell-item>
        <e-cell-item style="text-align: right;">
          <el-button type="link" @click="beforeDownloadExcel('score')">下载成绩模板</el-button>
          <e-file-upload
            style="position:relative"
            accept=".xlsx,.xls"
            class="upload-demo"
            :action="uploadScoreUrl"
            :on-error="errorUpload"
            @success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
            @exception="hanleException">
            <el-button size="small" title="点击上传文件“批量导入学员成绩.xlsx”">导入学员成绩</el-button>
          </e-file-upload>
        </e-cell-item>
      </e-cellbox>
      <div class="student-table">
        <el-table
          :data="train_student_list.list"
          ref="multipleTable"
          @selection-change="handleSelectionChange" 
          tooltip-effect="dark" 
          v-bind="getTableProps()"
          empty-text="暂无学员"
          @sort-change="handelOrder">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column 
            prop="name"
            label="姓名"
            sortable 
            align="center">
            <template slot-scope="scope">
              <span class="link" @click="handleDetail(scope.$index, scope.row)">
                {{ scope.row.name }}
              </span>
            </template>
          </el-table-column>
          <el-table-column 
            label="性别" 
            width="60" 
            align="center">
            <template slot-scope="scope">
              <span>{{scope.row.sex === 1 ? '男': scope.row.sex === 2 ? '女' : '未知'}}</span>  
            </template>
          </el-table-column>
          <el-table-column 
            prop="age" 
            label="年龄" 
            width="70" 
            sortable 
            align="center">
            <template slot-scope="scope">
              {{scope.row.age === '' ? '未知': scope.row.age}}
            </template>
          </el-table-column>
          <el-table-column 
            prop="school" 
            label="校区"
            :show-overflow-tooltip="true"
            width="160" 
            align="center">
            <template slot-scope="scope">
              {{scope.row.schoolName || '未知'}}
            </template>
          </el-table-column>
          <el-table-column  
            label="在上课程"
            :show-overflow-tooltip="true"
            width="200"
            align="center">
            <template slot-scope="scope">
              {{ scope.row.courseInfo }}
            </template>   
          </el-table-column>
          <el-table-column
            label="课程数"
            align="center"
            width="70">
            <template slot-scope="scope">
              {{ scope.row.courseNum ? scope.row.courseNum : 0}}
            </template>
          </el-table-column>
          <el-table-column 
            prop="operate" 
            label="操作" 
            width="90" 
            align="center">
            <template slot-scope="scope">
              <p><el-button @click="handleEdit(scope.$index, scope.row)"  type="link">编辑</el-button></p>
              <!-- 
                <p><el-button @click="handleVacate(scope.$index, scope.row)" v-if="scope.row.courseNum" type="link">请假</el-button></p>
                <p><el-button @click="handleCancelVacate(scope.$index, scope.row)" v-if="scope.row.needCancelLeave === 1" type="link">撤销请假</el-button></p>
                <p><el-button @click="handleDispose(scope.$index, scope.row)" type="link" v-if="scope.row.needConsume === 1 ">销课</el-button></p>
                <p><el-button @click="handleCancelDispose(scope.$index, scope.row)" type="link" v-if="scope.row.needCancelConsume === 1">撤销销课</el-button></p>
                <p><el-button @click="handleRepair(scope.$index, scope.row)" v-if="scope.row.needMakeup === 1" type="link">补课</el-button></p>
              -->
              <p><el-button @click="handleRemove(scope.$index, scope.row)" v-if="scope.row.courseNum === 0" type="link">删除</el-button></p>
              <p><el-button @click="handleTestPoint(scope.$index, scope.row)" type="link">测试成绩</el-button></p>
              <p><el-button type="link" @click="checkBirthday(scope.row.id)">身体数据</el-button></p>
            </template>
          </el-table-column>
        </el-table>
         <el-pagination
          v-bind="getPaginationProps(train_student_list)"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          >
        </el-pagination> 
      </div>
      <vacate :isVacate="isVacate" :studentInfo="studentInfo" v-if="isClose" v-model="isClose" @success="handleSuccessList" />
      <repair :makeup="makeup" v-if="isRepair" v-model="isRepair" @success="handleSuccessList" />
      <dispose-course :isDispose="isDispose" :isStudentDispose="isStudentDispose" :studentInfo="studentInfo" v-if="isDisposeClose" v-model="isDisposeClose" @success="handleSuccessList" />
    </div>

    <BirthdayDialog
      v-if="dialogVisible"
      :visible="dialogVisible"
      @savebirthday="handleSave"
      @close="dialogVisible = false">
    </BirthdayDialog>
  </div>  
</template>

<script>
import { pagingList } from 'utils/mixins'
import vacate from './components/Vacate'
import repair from './components/Repair'
import disposeCourse from './components/DisposeCourse'
import { mapGetters } from 'vuex'
import trainApi from 'api/train'
import EInputNumberRange from '@e-ui/InputNumberRange'
import EFileUpload from '@e-ui/FileUpload'
import {downloadFile} from 'utils'
import BirthdayDialog from './components/chart/BirthdayDialog'

const DOWMLOAD_NUM = 2000 // 每次导出学员上限
export default {
  mixins: [pagingList],
  components: {
    vacate,
    repair,
    EInputNumberRange,
    disposeCourse,
    EFileUpload,
    BirthdayDialog
  },
  data () {
    return {
      dialogVisible: false,
      query: this.getQuery({name: this.$route.query.name || null, locationProvinceIdStr: this.$route.query.locationProvinceIdStr || null, locationCityIdStr: this.$route.query.locationCityIdStr || null, ageFrom: this.$route.query.ageFrom, ageTo: this.$route.query.ageTo, schoolIdStr: this.$route.query.schoolIdStr, showInClass: this.$route.query.showInClass || false}),
      isVacate: false, // 请假or撤销请假
      isDispose: false, // 销课or撤销销课
      isClose: false,
      isDisposeClose: false,
      studentInfo: {},
      repair: false, // 补课
      isRepair: false,
      makeup: {},
      loading: false,
      name: '',
      address: [],
      school: '',
      lastStepVisible: false,
      selectChecked: false,
      schoolCampus: '',
      campusData: [],
      multipleSelection: [],
      isStudentDispose: false,
      studentDetailInfo: {}
    }
  },
  computed: {
    ...mapGetters({
      train_student_list: 'train_student_list', // 学员列表数据
      train_compus_selection: 'train_compus_selection' // 学员列表数据
    }),
    numberRange: {
      set (value) {
        let toVal = value[1] === 0 ? null : value[1]
        let fromVal = value[0] < value[1] ? value[0] : toVal
        this.query.ageFrom = fromVal
        this.query.ageTo = value[0] > value[1] ? fromVal : toVal
      },
      get () {
        return [this.query.ageFrom || 0, this.query.ageTo || 0]
      }
    },
    uploadUrl () {
      return '/api/train/student/import'
    },
    uploadScoreUrl () {
      return '/api/train/student/importStudentScoreInfo'
    },
    selectionOption () {
      let option = []
      for (let i = 0; i < this.train_compus_selection.length; i++) {
        option.push({
          label: this.train_compus_selection[i].provinceName + '-' + this.train_compus_selection[i].cityName,
          value: this.train_compus_selection[i].provinceId + '-' + this.train_compus_selection[i].cityId
        })
      }
      return option
    },
    initValue: {
      set (value) {
        let valueArr = value.split('-')
        this.query.locationProvinceIdStr = valueArr[0] || null
        this.query.locationCityIdStr = valueArr[1] || null
      },
      get (value) {
        if (this.query.locationProvinceIdStr === null || this.query.locationCityIdStr === null) {
          return ''
        }
        value = this.query.locationProvinceIdStr + '-' + this.query.locationCityIdStr
        this.compusLoad(value)
        return value
      }
    }
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    beforeDownloadExcel (type) {
      // 默认配置
      let config = {
        url: '/api/train/student/downloadTemplate',
        fileName: '求苗-批量新增学员.xlsx'
      }
      // 成绩配置
      if (type === 'score') {
        config.url = '/api/train/student/scoreTemplateDownload'
        config.fileName = '求苗-批量录入学员成绩.xlsx'
      }
      this.downloadExcel(config)
    },
    downloadExcel ({url, fileName, errMsg}) {
      let _this = this
      downloadFile(url, fileName, function (blob) {
        _this.$message({
          message: errMsg || '下载出错，请稍后再试',
          type: 'warning'
        })
      })
    },
    handleUploadSuccess (res, file) {
      let [successMsg, errMsg] = res.msg.split(',')
      let successVNode = this.$createElement('div', {
        domProps: {
          innerHTML: successMsg.replace(/([0-9])+/g, (k) => `<span style="color: #24c881">${k}</span>`) // 成功肯定有 排在第一个
        }
      })
      let errVNode = !errMsg ? '' : this.$createElement('div', {
        domProps: {
          innerHTML: errMsg.replace(/([0-9])+/g, (k) => `<span style="color: #fd8223">${k}</span>`) // 失败不一定有 排在第二个
        }
      })
      let errFileVNode = !errMsg ? '' : this.$createElement('a', {
        'class': {
          'link': true
        },
        'attrs': {
          'href': res.data,
          'download': '导入错误数据.xlsx'
        },
        'style': {
          marginTop: '10px'
        }
      }, [
        '点击下载导入错误数据表[',
        this.$createElement('span', {}, [res.data.substring(res.data.lastIndexOf('/') + 1)]),
        ']'
      ])
      let messageVNode = this.$createElement('div', {
        style: {
          width: '180px',
          lineHeight: '25px',
          wordBreak: 'break-all'
        }
      }, [successVNode, errVNode, errFileVNode])
      this.$msgbox({
        title: '温馨提示',
        message: messageVNode,
        confirmButtonText: '我知道了',
        showCancelButton: false,
        type: 'warning'
      }).then(res => {
        this.fetch(this.query)
      }).catch(() => {})
    },
    beforeUpload (file) {
      console.log('beforeUpload', file)
    },
    errorUpload (res, file) {
      console.log('errorUpload', res, file)
      this.$message({
        message: '上传失败',
        type: 'warning'
      })
    },
    hanleException (res) {
      if (['40081', '40082'].includes(res.result)) {
        this.$confirm(res.msg, '温馨提示', {
          confirmButtonText: '我知道了',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {})
      } else {
        // 此处和 success处理相同 直接跳转处理
        this.handleUploadSuccess(res)
      }
    },
    handleAddStudent () { // 新增
      this.$router.push({name: 'addStudent'})
    },
    fetch (query) {
      this.$store.dispatch('train_student_list', query)
    },
    handelOrder (column, prop, order) {
      let query = Object.assign({sort: prop}, this.query)
      this.$store.dispatch('train_student_list', query)
    },
    handleDetail (index, row) {
      this.$router.push('/training/student/detail/' + row.id)
    },
    handleEdit (index, row) { // 编辑
      this.$router.push({name: 'editStudent', query: {id: row.id}})
    },
    handleVacate (index, row) { // 展示请假
      this.studentInfo = row
      this.isClose = true
      this.isVacate = true
    },
    handleCancelVacate (index, row) { // 展示撤销请假
      this.studentInfo = row
      this.isClose = true
      this.isVacate = false
    },
    handleDispose (index, row) { // 销课
      this.studentInfo = Object.assign({isCancelDispose: 0, isShowDispose: true}, row)
      this.isDisposeClose = true
      this.isDispose = true
      this.isStudentDispose = true
    },
    handleCancelDispose (index, row) { // 撤销销课
      this.studentInfo = Object.assign({isCancelDispose: 1, isShowDispose: true}, row)
      this.isDisposeClose = true
      this.isDispose = false
      this.isStudentDispose = false
    },
    handleRepair (index, row) { // 展示补课
      this.makeup = row
      this.repair = true
      this.isRepair = true
    },
    handleSuccessList () {
      this.fetch(this.query)
    },
    handleTestPoint (index, row) { // 测试学员成绩
      this.$router.push({path: '/training/student/test', query: {studentId: row.id}})
    },
    handleRemove (index, row) {
      this.$confirm('删除后将不可恢复，确认删除该学员吗？', '温馨提示', {type: 'warning'}).then(() => {
        trainApi.removeStudent({id: row.id}, {
          successMsg: '删除成功'
        }).then(res => {
          this.fetch(this.query)
        })
      })
    },
    handleExportComm () {
      let paramsStr = ''
      let fileName = '学员名单.xlsx'
      let url = '/api/train/student/studentInfoExport'
      let {sort, schoolIdStr} = this.query
      let [ageToData, ageFromData] = this.numberRange
      let params = {
        sortData: sort || '',
        ageToData: ageToData || '',
        schoolId: schoolIdStr || '',
        name: this.query.name || '',
        ageFromData: ageFromData || '',
        importNum: this.$exportNum || 1
      }
      Object.keys(params).forEach((item, index) => {
        let base = `${item}=${params[item]}`
        paramsStr += index === 0 ? '?' + base : '&' + base
      })
      downloadFile(url + paramsStr, fileName)
    },
    handleExportStudent () { // 导出学员
      // 初始化 学员 总数
      this.$exportNum = isNaN(this.$exportNum) ? 0 : this.$exportNum
      this.$totalNum = isNaN(this.$totalNum) ? this.train_student_list.total : this.$totalNum
      if (this.$totalNum <= 0) {
        // 终止 并初始化
        this.$exportNum = 0
        this.$totalNum = this.train_student_list.total
        return false
      }
      if (this.$totalNum > 0 && this.$exportNum) {
        // 此处处理 继续下载
        this.$msgbox({
          title: '温馨提示',
          message: <div>
            <h1 style="font-size: 15px">导出成功！</h1>
            <div style="margin-top: 10px; font-size: 14px; color:#666;">点击继续导出导出剩下的数据</div>
          </div>,
          showCancelButton: true,
          confirmButtonText: '继续导出',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          this.$exportNum ++
          this.$totalNum -= DOWMLOAD_NUM
          this.handleExportComm()
          this.handleExportStudent()
        }).catch(() => {})
      } else if (this.$totalNum < DOWMLOAD_NUM) {
        // 此处处理首次进入且总数不超过2000
        this.handleExportComm()
      } else {
        // 此处处理 首次进入 且总数大于2000
        this.$msgbox({
          title: '温馨提示',
          message: <div>
            <h1 style="font-size: 15px">一次最多可导出2000条数据</h1>
            <div style="margin-top: 10px; font-size: 14px; color:#666;">更多的数据可分次导出</div>
          </div>,
          confirmButtonText: '好的',
          showCancelButton: false,
          type: 'warning'
        }).then(res => {
          this.$exportNum ++
          this.$totalNum -= DOWMLOAD_NUM
          this.handleExportComm()
          this.handleExportStudent()
        }).catch(() => {})
      }
    },
    // 加载校区数据
    compusLoad (value) {
      value = value.toString().split('-')
      trainApi.getSchoolListByProCity({provinceId: value[0] || '', cityId: value[1]}).then((res) => {
        if (res.result === '0') {
          this.campusData = res.data
          // this.schoolCampus = res.data[0].schoolName
          // this.query.schoolIdStr = res.data[0].id
          // this.query.schoolIdStr = this.query.schoolIdStr ? this.query.schoolIdStr : res.data[0].schoolName
        }
      })
    },
    campusChange (value) {
      this.query.schoolIdStr = value
    },
    locationClear () {
      this.query.schoolIdStr = ''
      this.schoolCampus = ''
      this.campusData = []
    },
    checkBirthday (id) {
      trainApi.studentDetail({studentId: id}).then(res => {
        this.studentDetailInfo = res.data
        if (this.studentDetailInfo.birthday) {
          this.$router.push({
            path: '/training/student/chart',
            query: Object.assign({}, {id: this.studentDetailInfo.id})
          })
        } else {
          this.dialogVisible = true
        }
      })
    },
    handleSave (birthday) {
      let data = Object.assign({}, this.studentDetailInfo, {birthday: birthday})
      trainApi.saveStudentBirthday(JSON.stringify(data), {context: this, successMsg: '修改成功'}).then(res => {
        this.dialogVisible = false
        this.$router.push({
          path: '/training/student/chart',
          query: Object.assign({}, {id: this.studentDetailInfo.id})
        })
      })
    }
  },
  watch: {
    'initValue' (newVl) {
      newVl = newVl || ''
      if (newVl.length === 0) {
        this.query.schoolIdStr = ''
      }
      if (!this.$firstRender && newVl) {
        this.compusLoad(newVl)
        this.$firstRender = true
      }
    }
  },
  mounted () {
    trainApi.schoolList({
      page: 1,
      rows: 100000
    }).then((res) => {
      this.campusData = res.data.list
    })
    this.$store.dispatch('train_compus_selection')
  }
}
</script>

<style lang="scss">
.content {
  .student-manage {
    margin-top: -25px;
    .cell-item:last-child {
      position: relative;
      .el-button{
        vertical-align:middle;
        margin-left:10px;
      }
    }
  }
  .search-mines {
    .form-search {
      .age-box {
        .el-input {
          width: 100%;
        }
      }
    }
  }
  .selected_student_list {
    margin-bottom: 10px;
    .cell-item:last-child {
      position: relative;
      .el-button{
        vertical-align:middle;
        margin-left:10px;
      }
    }
  }
}
.form-search .el-form-item__content > .el-input,.form-search .el-form-item__content > .el-cascader, .form-search .el-form-item__content > .el-select{
  width:auto;
}
.showErrorData{
  display: none;
}
</style>
